package com.shenzw.mybatisdemo.aop;

import com.alibaba.fastjson.JSON;
import com.shenzw.mybatisdemo.utils.NetUtils;
import lombok.Builder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 请求参数切面
 *
 * @author shenzw
 * @date 2024/1/8
 */
@Component
@Aspect
@Slf4j
public class RequestLogAspect {

    /**
     * 定义切入点（扫描全部controller）
     *
     * @Pointcut("execution(* com.leadingtek.glbank.settlement.reconciliation.web..*(..)) " +
     * "|| execution(* com.leadingtek.glbank.settlement.settlement.web..*(..)) " +
     * "|| execution(* com.leadingtek.glbank.settlement.orderAccounting.web..*(..))")
     */
    @Pointcut("execution(* com.shenzw.mybatisdemo.controller..*(..))")
    public void requestServer() {
    }

    /**
     * 正常环绕通知
     */
    @Around("requestServer()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        Object result = proceedingJoinPoint.proceed();
        try {
            RequestInfo requestInfo = RequestInfo.builder()
                    .ip(NetUtils.getClientIpAddress(request))
                    .url(request.getRequestURL().toString())
                    .httpMethod(request.getMethod())
                    .classMethod(String.format("%s.%s", proceedingJoinPoint.getSignature().getDeclaringTypeName(),
                            proceedingJoinPoint.getSignature().getName()))
                    .requestParams(getRequestParamsByJoinPoint(proceedingJoinPoint))
                    .result(result)
                    .timeCost(System.currentTimeMillis() - start)
                    .build();
            log.info("Request Info = {}", JSON.toJSONString(requestInfo));
        } catch (Exception e) {
            log.error("日志切面出现异常", e);
        }

        return result;
    }


    /**
     * 异常环绕通知 对于异常，耗时是没有意义的，因此不统计耗时，而是添加了异常的打印
     *
     * @param joinPoint 切点
     * @param e         运行时异常
     */
    @AfterThrowing(pointcut = "requestServer()", throwing = "e")
    public void doAfterThrow(JoinPoint joinPoint, RuntimeException e) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        RequestErrorInfo requestErrorInfo = RequestErrorInfo.builder()
                .ip(NetUtils.getClientIpAddress(request))
                .url(request.getRequestURL().toString())
                .httpMethod(request.getMethod())
                .classMethod(String.format("%s.%s", joinPoint.getSignature().getDeclaringTypeName(),
                        joinPoint.getSignature().getName()))
                .requestParams(getRequestParamsByJoinPoint(joinPoint))
                .exception(getStackTraceAsString(e))
                .build();
        log.info("Error Request Info = {}", JSON.toJSONString(requestErrorInfo));
    }

    /**
     * 获取入参
     *
     * @param joinPoint 切点
     * @return Map<String, Object>
     */
    private Map<String, Object> getRequestParamsByJoinPoint(JoinPoint joinPoint) {
        // 参数名
        String[] paramNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames();
        // 参数值
        Object[] paramValues = joinPoint.getArgs();

        return buildRequestParam(paramNames, paramValues);
    }

    /**
     * 构建请求参数
     *
     * @param paramNames  参数名
     * @param paramValues 参数名称
     * @return Map<String, Object>
     */
    private Map<String, Object> buildRequestParam(String[] paramNames, Object[] paramValues) {
        Map<String, Object> requestParams = new HashMap<>(16);
        for (int i = 0; i < paramNames.length; i++) {
            Object value = paramValues[i];
            if (value instanceof BeanPropertyBindingResult) {
                continue;
            } else if (value instanceof HttpServletRequest || value instanceof HttpServletResponse) {
                continue;
            }

            // 如果是文件对象
            if (value instanceof MultipartFile) {
                MultipartFile file = (MultipartFile) value;
                // 获取文件名
                value = file.getOriginalFilename();
            }

            requestParams.put(paramNames[i], value);
        }

        return requestParams;
    }

    /**
     * 封装异常信息
     *
     * @param e 异常信息
     * @return String
     */
    private String getStackTraceAsString(Throwable e) {
        if (e == null) {
            return "";
        }
        StringWriter stringWriter = new StringWriter();
        e.printStackTrace(new PrintWriter(stringWriter));
        return stringWriter.toString();
    }

    /**
     * 正常的请求信息
     */
    @Data
    @Builder
    public static class RequestInfo {
        /**
         * ip地址
         */
        private String ip;
        /**
         * URL地址
         */
        private String url;
        /**
         * 请求方式
         */
        private String httpMethod;
        /**
         * 类名
         */
        private String classMethod;
        /**
         * 请求参数
         */
        private Object requestParams;
        /**
         * 响应结果
         */
        private Object result;
        /**
         * 请求耗时
         */
        private Long timeCost;
    }

    /**
     * Runtime请求异常信息
     */
    @Data
    @Builder
    public static class RequestErrorInfo {
        /**
         * ip地址
         */
        private String ip;
        /**
         * URL地址
         */
        private String url;
        /**
         * 请求方式
         */
        private String httpMethod;
        /**
         * 类名
         */
        private String classMethod;
        /**
         * 请求参数
         */
        private Object requestParams;
        /**
         * 异常信息
         */
        private String exception;
    }
}
